from pos import Position

import stackless
from log import getLogger

logger=getLogger('charector')
from actor import Extended,Actor
from items import Bomb

import items

from event import Event

class Charector(Extended,Actor,items.DestroyAble):

    vectors={
            'left':(-1,0),
            'right':(1,0),
            'up':(0,-1),
            'down':(0,1)
            }

    def __init__(self,world_,pos):
        Actor.__init__(self)
        
        Extended.__init__(self,world_,pos,IsCharector=True)

        self.value=0

    def defaultEventHandler(self):
        while True:

            event=self.channel.receive()

            if event.subject=='input' :
                
                self.cmd(event.event)

            elif event.subject=='get':
                self.got(event.obj)

            elif event.subject=='destroy':

                logger.debug('destroy')
                self.remove()
                self.display.lose()
                stackless(self.world.channel.send)(Event(subject='lose'))

                del self

                break

            elif event.subject=='quit':
                break
                

            stackless.schedule()


class BasicCharector(Charector):
    def cmd(self,cmd):
            if cmd=='set' :
                Bomb(self.world,self.pos)

            elif 'change' in cmd :
                pos=Position(tuple(map(int,cmd.split()[1:])))

                self.pos=pos
                logger.debug(pos)
                self.update()

            elif cmd in self.vectors:

                logger.debug('going'+cmd)
                old_pos=self.pos
                self.pos=Position(self.pos[0]+self.vectors[cmd][0],self.pos[1]+self.vectors[cmd][1])

                collsions=self.world.getCollisions(self.pos,obj=self)

                for item in collsions:
                    if isinstance(item,items.PickAble):
                        item.picked(obj=self)
                    else:
                        self.pos=old_pos
                        break

                if self.pos!=old_pos:
                    logger.debug('sending move event to world')
                    self.update()

    def got(self,obj):

        if isinstance(obj,items.Gold):
            self.value+=obj.value

            logger.debug(self.value)

    def destroyed(self,obj):
        self.display.lose()
        stackless(self.world.channel.send)(Event(subject='lose'))
        self.remove()

        del self

